<template>
  <div class="system-info">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的待办</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 流程名称 -->
            <el-form-item label="流程名称">
              <el-select
                v-model="formInline.flowId"
                filterable
                auto-complete="off"
                placeholder="请选择"
                style="width:150px;"
              >
                <el-option label="无" value></el-option>
                <!-- 循环所有角色 角色名称 角色ID -->
                <el-option
                  v-for="(item,index) in flowList"
                  :key="index"
                  :label="item.flowName"
                  :value="item.flowId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发起人">
              <!-- 员工选择框子组件 -->
              <user-sel :users="users" @seluser="selUser"></user-sel>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 数据列表 -->
        <el-table :data="menusData" border style="width: 100%" height="395" ref="menusData">
          <!-- 流程编号 -->
          <el-table-column :show-overflow-tooltip="true" prop="flowCode" label="流程编号"></el-table-column>
          <!-- 发起人 -->
          <el-table-column label="发起人" align="center" width="100">
            <template slot-scope="scope">{{ scope.row.flowOriginator | getName(users) }}</template>
          </el-table-column>
          <!-- 工单优先级 -->
          <el-table-column align="center" label="优先级" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.flowPriority === 0">
                普通
              </span>
              <span v-if="scope.row.flowPriority === 1">
                重要
              </span>
              <span v-if="scope.row.flowPriority === 2">
                紧急
              </span>
            </template>
          </el-table-column>
           <!-- 申请日期 时间格式过滤 -->
          <el-table-column label="申请日期" align="center" width="120">
            <template slot-scope="scope">{{ scope.row.flowOriginatorTime | filterTime }}</template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="400"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 详细信息 -->
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnDel">详细信息</el-button>
              <!-- 立即申请 -->
              <el-button type="success" size="mini" @click="agreed(scope.row)" v-if="btnDel">通过</el-button>
              <!-- 重新申请 -->
              <el-button type="warning" size="mini" @click="refused(scope.row)" v-if="btnEdit">驳回</el-button>
              <!-- 修改编辑 -->
              <el-button type="primary" size="mini" @click="entrust(scope.row)" v-if="btnEdit">委托</el-button>
              <!-- 审批历史 -->
              <el-button type="info" @click="history(scope.row)" size="mini" v-if="btnEdit">历史</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>

      <!-- 弹窗 新增or修改 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <!-- 添加、修改表单 -->
        <el-form ref="editForm" :model="editForm" label-width="80px">
          <el-form-item label="委托人">
            <user-sel :users="users" @seluser="selEntrustUser"></user-sel>
          </el-form-item>
          <el-form-item label="审批意见">
            <el-input type="textarea" :rows="3" placeholder="审批意见(20字以内)" v-model="editForm.note"></el-input>
          </el-form-item>
          <el-form-item label="优先级">
            <el-radio-group v-model="editForm.flowPriority">
              <el-radio label="0">普通</el-radio>
              <el-radio label="1">重要</el-radio>
              <el-radio label="2">紧急</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="消息推送">
            <el-checkbox-group v-model="editForm.msgPush">
              <el-checkbox label="1">站内消息通知</el-checkbox>
              <el-checkbox label="2">企业微信通知</el-checkbox>
              <el-checkbox label="3">邮件通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <!-- 添加 初始化弹窗表单数据 -->
          <el-button v-if="dialogStatus=='create'" @click="subEntrust" type="primary" :disabled="isSubmit">确认</el-button>
        </div>
      </el-dialog>

      <el-dialog title="流程图" :visible.sync="modalVisible" width="600px">
        <div class="flowLog">
          <el-table
            :data="historyLog"
            border
            style="width: 100%">
            <!-- 处理人 -->
            <el-table-column label="处理人" align="center" width="100">
              <template slot-scope="scope">{{ scope.row.createUserId | getName(users) }}</template>
            </el-table-column>
            <!-- 处理日期 时间格式过滤 -->
            <el-table-column label="处理日期" align="center" width="120">
              <template slot-scope="scope">{{ scope.row.createTime | filterTime }}</template>
            </el-table-column>
            <el-table-column align="center" label="结果" width="60">
              <template slot-scope="scope">
                <!-- 处理结果 1.发起 2.通过 3.驳回 4.取消 -->
                <span v-if="scope.row.result === 1">
                  发起
                </span>
                <span v-if="scope.row.result === 2">
                  通过
                </span>
                <span v-if="scope.row.result === 3">
                  驳回
                </span>
                <span v-if="scope.row.result === 4">
                  取消
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="note"
              label="审批说明">
            </el-table-column>
          </el-table>
        </div>
        <node-data ref="nodeFlow" :nodeData="nodeData"></node-data>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';
// 引入员工选择组件
import userSel from '@/components/UserSel/index.vue';
// 节点数据
import NodeData from '@/components/NodeData';

export default {
  // 注册组件
  components: {
    userSel,
    NodeData
  },
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有流程模型数据
    this.getFlowList();

    // 获取所有员工
    this.getUsers();

    // 加载分页数据
    this.getmenusDataByPage();
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD');
    },
    // 发起人过滤
    getName (value, params) {
      for (let i = 0; i < params.length; i++) {
        if (params[i].userId === value) {
          return params[i].userName;
        }
      }
    }
  },

  // 当前页面数据
  data () {
    return {
      // 流程图预览数据
      nodeData: {},
      modalVisible: false,
      flowList: [],
      // 审批历史数据
      historyLog: [],
      // 屏蔽重复提交
      isSubmit: false,
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取所有用户
      users: [],
      // 用户选择框子组件选中值
      getUser: [],
      entrusUser: [],

      // 搜索条件
      formInline: {
        flowId: '',
        flowOriginator: ''
      },

      // 表单初始化数据
      editForm: {
        flowPriority: '',
        msgPush: [],
        note: ''
      },

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',
      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '委托信息'
      },
      // 弹窗是否显示
      dialogFormVisible: false
    };
  },

  methods: {
    // 委托他人
    entrust (row) {
      // 弹窗类型
      this.dialogStatus = 'create';
      // 弹窗显示状态
      this.dialogFormVisible = true;

      // 表单数据重置
      this.entrustUser = [];
      // 弹窗表单初始化数据
      this.editForm = Object.assign({}, row);
      // 重置新增界面默认数据
      this.editForm.flowPriority = '';
      this.editForm.msgPush = [];
      this.editForm.note = '';
    },

    // 提交委托
    subEntrust () {
      let params = {
        // 工单编号
        flowCode: this.editForm.flowCode,
        // 发起人
        flowOriginator: this.editForm.flowOriginator,
        // 当前审批节点
        flowCurrentNode: this.editForm.flowCurrentNode,
        // 当前审批人
        flowCurrentUser: this.entrusUser[0],
        // 工单状态
        status: 3,
        // 处理结果
        result: this.editForm.flowCurrentNode + ', 流程已委托处理！',
        // 工单优先级
        flowPriority: this.editForm.flowPriority,
        // 消息推送
        msgPush: this.editForm.msgPush.toString(),
        // 审批历史-审批节点
        flowNode: this.editForm.flowCurrentNode,
        // 审批历史-审批意见
        note: this.editForm.note,
        // 审批历史-审批结果
        workResult: 2
      };

      this.$http.raw('api/updateOrderStatus', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '操作成功，已委托处理！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.getmenusDataByPage();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 驳回申请
    refused (row) {
      // 初始数据源
      let list = JSON.parse(row.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = list.nodes[0].id;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      let params = {
        // 工单编号
        flowCode: row.flowCode,
        // 发起人
        flowOriginator: row.flowOriginator,
        // 当前审批节点
        flowCurrentNode: setUpNodeId,
        // 当前审批人
        flowCurrentUser: row.flowOriginator,
        // 工单状态
        status: 5,
        // 处理结果
        result: row.flowCurrentNode + ', 申请被驳回！',
        // 工单优先级
        flowPriority: row.flowPriority,
        // 消息推送
        msgPush: row.msgPush,
        // 审批历史-审批节点
        flowNode: row.flowCurrentNode,
        // 审批历史-审批意见
        note: row.note,
        // 审批历史-审批结果
        workResult: 3
      };

      this.$http.raw('api/updateOrderStatus', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '审批成功，已驳回申请！',
            type: 'success'
          });
          this.getmenusDataByPage();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 通过申请
    agreed (row) {
      // 初始数据源
      let list = JSON.parse(row.flowJson);
      // 获取发起节点的ID
      let setUpNodeId = row.flowCurrentNode;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });
      let end = '';
      for (let i = 0; i < list.nodes.length; i++) {
        if (nextNode.length === 1) {
          if (nextNode[0] === list.nodes[i].id) {
            end = list.nodes[i].type;
          }
        }
      }
      if (end === '结束') {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          // 发起人
          flowOriginator: row.flowOriginator,
          // 当前审批节点
          flowCurrentNode: nextNode.toString(),
          // 当前审批人
          flowCurrentUser: '',
          // 工单状态
          status: 4,
          // 处理结果
          result: setUpNodeId + ', 审批已通过并结束！',
          // 工单优先级
          flowPriority: '',
          // 消息推送
          msgPush: '',
          // 审批历史-审批节点
          flowNode: setUpNodeId,
          // 审批历史-审批意见
          note: '',
          // 审批历史-审批结果
          workResult: 2
        };

        this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            this.$message({
              message: '审批成功，已批准通过！',
              type: 'success'
            });
            this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      } else {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          // 发起人
          flowOriginator: row.flowOriginator,
          // 当前审批节点
          flowCurrentNode: nextNode.toString(),
          // 当前审批人
          flowCurrentUser: users[0].toString(),
          // 工单状态
          status: 3,
          // 处理结果
          result: setUpNodeId + ', 审批已通过！',
          // 工单优先级
          flowPriority: row.flowPriority,
          // 消息推送
          msgPush: row.msgPush,
          // 审批历史-审批节点
          flowNode: setUpNodeId,
          // 审批历史-审批意见
          note: row.note,
          // 审批历史-审批结果
          workResult: 2
        };
        this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            this.$message({
              message: '审批成功，已批准通过！',
              type: 'success'
            });
            this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }
    },

    getCls (data) {
      this.drawer = data;
    },

    // 获取所有用户
    getUsers () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取用户选择框选中值
    selUser (data) {
      this.getUser = data;
    },

    selEntrustUser (data) {
      this.entrusUser = data;
    },

    editHandle: function (row) {
      let params = {
        flowId: row.flowId
      };
      this.$http.post('api/findFlowRouter', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$router.push({
            path: res.datas,
            query: {
              node: 3,
              datas: row
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有流程数据
    getFlowList: function () {
      this.$http.raw('api/findAllFlow').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.flowList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    },

    // 审批历史
    history: function (row) {
      let params = {
        flowCode: row.flowCode
      };
      this.$http.post('api/findWorkResultList', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          let currentNode = row.flowCurrentNode;
          let flowJson = JSON.parse(row.flowJson);
          flowJson.nodes.map(item => {
            if (item.id === currentNode) {
              item.color = '#FF0000';
            }
          });
          // 流程图预览
          this.modalVisible = true;
          this.nodeData = flowJson;
          this.historyLog = res.datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询
    selHandle: function () {
      // 收集请求数据
      let params = {
        flowId: this.formInline.flowId === null ? '' : this.formInline.flowId,
        flowOriginator: this.getUser[0],
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      // 根据公司ID请求对应分页数据结果
      this.$http.raw('api/findOrderByFlowIdAndOUser', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      // 收集请求参数
      let params = {
        flowId: '',
        flowOriginator: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      this.$http.raw('api/findOrderByFlowIdAndOUser', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    }
  }
};
</script>

<style lang='scss'>
@import './index.scss';
</style>
